#include "stdafx.h"

#include "MyControls/CircleTool.h"
#include <MyViews/ZoomBench.h>
#include "math/round.h"

namespace My {

CircleTool::CircleTool(ZoomBench & owner, int StartSize)
	: WireTool(owner)
{
	CreateCircleBitmap(StartSize);
}

point<int> CircleTool::GetWireBenchTopLeft(CPoint p) const
{
	point<float> c = GetBench().ClientToBench(p);
	return point<int>(round(c.x) - GetSize(), round(c.y) - GetSize());
}

rect<int> CircleTool::GetWireBenchRect(CPoint p) const
{
	point<int> tl = GetWireBenchTopLeft(p);
	return rect<int>(tl.x, tl.y, tl.x+GetDoubleSize(), tl.y+GetDoubleSize());
}

void CircleTool::IncreaseSize(int inc)
{
	int OldSize = GetSize();
	int size = OldSize + inc;
	unsigned int max = 150;
	if (size < 1)
		size = 1;
	if (size > max)
		size = max;
	if (size != OldSize) {
		if (IsWireVisible())
			HideWire();
		CreateCircleBitmap(size);
		ShowWire();
	}
}

CRect CircleTool::GetWireRect(CPoint p)
{
	int s = int(GetSize() * GetBench().GetScale());
	CRect r(p, p);
	r.InflateRect(s, s, s + 1, s + 1);
	return r;
}

void CircleTool::DrawWire(CDC * pDC, CPoint p, int width)
{
	CPen pen(PS_SOLID, width, RGB(0, 0, 0));
	CPen * old_pen = pDC->SelectObject(&pen);

	CBrush brush;
	brush.CreateStockObject(HOLLOW_BRUSH);
	CBrush * old_brush = pDC->SelectObject(&brush);

	int nROP = pDC->SetROP2(R2_NOTXORPEN);

	pDC->Ellipse(GetWireRect(p));

	pDC->SetROP2(nROP);

	pDC->SelectObject(old_pen);
	pDC->SelectObject(old_brush);
}

void CircleTool::CreateCircleBitmap(int radius)
{
	CircleBitmap(m_CircleBitmap, radius);
}

void CircleTool::CircleBitmap(img::bitmap & bmp, int radius)
{
	bmp.resize(2*radius, 2*radius);
	img::bitmap::iterator i;
	double sq_radius = square(radius);
	for (i = bmp.begin(); i != bmp.end(); ++i) {
		*i = (square(i.x() - (radius-0.5)) + square(i.y() - (radius-0.5))) < sq_radius;
	}
}

} //namespace My
